<?php

namespace mybackend\controllers;

use common\error\ErrorCode;
use common\support\VerfCodeManage;
use Yii;
use yii\filters\AccessControl;
use common\services\myhtsq\ErpInterfaceService;
use common\services\myhtsq\RoleService;

/**
 * Site controller
 */
class SiteController extends BaseController
{


    public function __construct($id, $module, $config = [])
    {
        parent::__construct($id, $module, $config);
    }

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['login', 'login-data', 'error', 'verf-code', 'query-test', 'clear-cache', 'get-auth-actions', 'check-action', 'get-static-url'],
                        'allow' => true,
                    ],
                    [
                        'actions' => ['logout', 'index', 'clear-cache'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ]
        ];
    }

    /**
     * @inheritdoc
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'common\actions\SystemError',
            ],
        ];
    }

    /**
     * @desc 跳转首页
     * @method get
     * @return type
     */
    public function actionIndex()
    {
        if (isset(Yii::$app->params["root-page"])) {
            return $this->redirect(Yii::$app->params["root-page"]);
        } else {
            return $this->render("index");
        }
    }

    /**
     * @desc 按模块获取验证码。登录模块为login
     * @method get
     * @param $module
     */
    public function actionVerfCode($module)
    {
        VerfCodeManage::responseVerfCode($module);
    }

    /**
     * @desc 登录提交操作
     * @method post
     * @body usercode=&password=&verfcode=
     * @return type
     */
    public function actionLogin($kfs = '')
    {
        $usercode = isset($_POST["usercode"]) ? $_POST["usercode"] : '';
        $password = isset($_POST["password"]) ? $_POST["password"] : '';
        $verfcode = isset($_POST["verfcode"]) ? $_POST["verfcode"] : '';

        if (!VerfCodeManage::validVerfCode("login", $verfcode)) {
            $error = "验证码输入错误！";
            if ($this->isAjaxRequest()) {
                return $this->json(array(
                    "retCode" => '-1',
                    "errMsg" => $error
                ));
            } else {
                return $this->toLoginPage(['error' => $error, 'kfs' => $kfs]);
            }
        }
        $result = ErpInterfaceService::getUserByCodeAndPassword($usercode, $password);

        $error = '';
        if (is_null($result)) {
            $error = "账号或者密码不正确";
        } else if ($result->IsDisabeld) {
            $error = "您的用户已经被禁用";
        } else if (!$result->CanLogin) {
            $error = "您的用户不允许登陆";
        }

        if (!empty($error)) {
            if ($this->isAjaxRequest()) {
                return $this->json(array(
                    "retCode" => '-1',
                    "errMsg" => $error
                ));
            } else {
                return $this->toLoginPage(['error' => $error]);
            }
        }

        call_user_func(Yii::$app->user->identityClass . "::clearCache", $usercode);
        $user = call_user_func(Yii::$app->user->identityClass . "::findIdentity", $usercode);
        Yii::$app->user->login($user);

        if ($this->isAjaxRequest()) {
            return $this->json(array(
                "retCode" => ErrorCode::SUCCESS,
            ));
        } else {
            return $this->goHome();
        }
    }

    /**
     * 跳转登录页
     * @param type $parameters
     * @return boolean
     */
    public function toLoginPage($parameters = [])
    {
        $page = '/login.html';
        if (isset(Yii::$app->params["login-page"])) {
            $page = Yii::$app->params["login-page"];
        }
        if (count($parameters) == 0) {
            Yii::$app->getResponse()->redirect($page);
        } else {
            $paraArr = [];
            foreach ($parameters as $key => $item) {
                $paraArr[] = $key . '=' . urlencode($item);
            }
            Yii::$app->getResponse()->redirect($page . '?' . join("&", $paraArr));
        }
        Yii::$app->end();
        return true;
    }

    /**
     * @desc 获取登录信息
     * @method get
     * @return type
     */
    public function actionLoginData()
    {
        return $this->json(array(
            "retCode" => ErrorCode::SUCCESS,
            "data" => array(
                "isGuest" => Yii::$app->user->isGuest,
                "userName" => Yii::$app->user->isGuest ? "" : Yii::$app->user->identity->username,
                "userGuid" => Yii::$app->user->isGuest ? "" : Yii::$app->user->identity->userguid,
            )
        ));
    }

    /**
     * @desc 注销
     * @method post
     */
    public function actionLogout()
    {
        Yii::$app->user->logout();

        if ($this->isAjaxRequest()) {
            return $this->json(array(
                "retCode" => ErrorCode::SUCCESS,
            ));
        } else {
            return $this->toLoginPage();
        }
    }

    /**
     * @desc 清除缓存
     * @method post
     * @return string
     */
    public function actionClearCache()
    {
        Yii::$app->cache->flush();
        return $this->json(array(
            ErrorCode::SUCCESS
        ));
    }

    public function actionCheckAction()
    {
        if (Yii::$app->user->isGuest) {
            return false;
        }
        $actionId = isset($_POST["actionId"]) ? $_POST["actionId"] : '';
        $auths = RoleService::getAuthCache(Yii::$app->user->identity->userguid);
        $actions = array_values(array_unique($auths));
        return $this->json(array(
            "retCode" => !empty($actions) && in_array($actionId, $actions)
        ));
    }

    public function actionGetAuthActions()
    {
        if (Yii::$app->user->isGuest) {
            return false;
        }
        $auths = RoleService::getAuthCache(Yii::$app->user->identity->userguid);
        $actions = array_values(array_unique($auths));
        return $this->json(array(
            "retCode" => ErrorCode::SUCCESS,
            "data" => $actions
        ));
    }

    public function  actionGetStaticUrl(){
        //静态站点地址,读取配置文件
        if(isset(Yii::$app->params["static_web_url"])){
            $staticurl = Yii::$app->params["static_web_url"];
            return $this->json(array(
                "retCode" => ErrorCode::SUCCESS,
                "data" => $staticurl
            ));
        }else{
            return $this->json(array(
                "retCode" => ErrorCode::ERR_QMYX_AGENCY_MANAGE_GET_EMPTY,
                "data" => ''
            ));
        }
        return false;
    }
}
